package com.itheima.config.aspect;

import com.alibaba.fastjson.JSON;
import com.itheima.mapper.DeptLogMapper;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.service.DeptLogService;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect//切面类
public class AopAspectMyLog {
        //编写aop的过程
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    OperateLogMapper operateLogMapper;

    //编写方法 注解过程
    @Around("@annotation(com.itheima.config.aspect.Mylog)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //记录开始时间
        long start = System.currentTimeMillis();
        //操作人的id 自增
        //获取请求头中的令牌
        String jwt = httpServletRequest.getHeader("token");
        //判断是否在里面
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer id = (Integer) claims.get("id");
        //获取当前操作人的时间
        LocalDateTime now = LocalDateTime.now();
        //获取它的操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取它的操作方法名
        String methodName = joinPoint.getSignature().getName();
        //获取方法的参数
        Object[] args = joinPoint.getArgs();
        //因为实体类中是String类型 所以要将数组转换一下
        String methodParams = Arrays.toString(args);
        //获取操作方法的返回值
        Object proceed = joinPoint.proceed();
        //将方法返回值转成 json
        String returnValue = JSON.toJSONString(proceed);



        //记录结束时间
        long end = System.currentTimeMillis();
        //操作耗时
        Long costTime=end-start;

        OperateLog operateLog = new OperateLog(null, id, now, className, methodName, methodParams, returnValue, costTime);
        //记录操作日志 添加到数据库中
        operateLogMapper.insert(operateLog);
        return proceed;
    }



}
